/**
 * @name: 公共方法封装
 * @date: 2020.3.5
 */
import Vue from 'vue'

var _this = new Vue();

//路径跳转-navigateTo
function navigateTo(path) {
	uni.navigateTo({
		url: path
	})
}

//弹窗提示-showToast-public
function showToast(msg) {
	uni.showModal({
		content: msg,
		showCancel: false
	})
}

//弹窗提示-showToast-success
function successToast(msg) {
	uni.showToast({
		title: msg,
		mask: true,
		duration: _this.$tmp.TIME_SUC
	})
}

//成功操作后返回上一页
function sucBack(n) {
	let m = !n ? 1 : n;
	setTimeout(() => {
		uni.navigateBack({
			delta: m
		})
	}, _this.$tmp.TIME_SUC);
}

//将数组转为逗号分隔的字符串
function arrToStr(arr) {
	let str = JSON.stringify(arr);
	str = str.replace(/\[/g, '');
	str = str.replace(/\]/g, '');
	return str.replace(/"/g, '');
}

/**
 * 带小数计算，保证精度
 * 把小数放大为整数(乘)，进行算术运算，再缩小为小数(除)
 * @param a {number} 运算数1
 * @param b {number} 运算数2
 * @param op {string} 运算类型，有加减乘除
 */
function operation(a, op, b) {
	let resu = 0; //运算后的结果
	let num1 = parseFloat(a);
	let num2 = parseFloat(b);
	switch (op) {
		case '+':
			resu = num1 + num2;
			break;
		case '-':
			resu = num1 - num2;
			break;
		case '*':
			resu = num1 * num2;
			break;
		case '/':
			resu = num1 / num2;
			break;
	}
	let str = resu.toString();
	let index = str.indexOf('.');
	if (index > -1) {
		//只截取两位小数，不进行四舍五入
		str = str.substring(0, (index + 3));
		resu = parseFloat(str);
	}
	return resu;
}

Vue.prototype.$navigateTo = navigateTo;
Vue.prototype.$showToast = showToast;
Vue.prototype.$successToast = successToast;
Vue.prototype.$sucBack = sucBack;
Vue.prototype.$arrToStr = arrToStr;
Vue.prototype.$operation = operation;

